package com.hbqyml.web.core.config;

import com.aliyun.oss.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.hbqyml.common.config.ParseDate;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;


/**
 * 阿里云oss工具类
 * @Author : 许雪恒
 * @date : 2021/9/4 9:04
 */
@Configuration
public class AliOssUtil {

    // endpoint oss-cn-beijing.aliyuncs.com
    @Value("${oss.endpoint}")
    private String endpoint ;
    // accessKey
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    // 空间
    @Value("${oss.bucketName}")
    private String bucketName;
    private OSS ossClient;


    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 向阿里云的OSS存储中存储文件  --file也可以用InputStream替代
     * @param file 上传文件
     * @return String 唯一MD5数字签名
     * */
    public String uploadObject2OSS(MultipartFile file) {
        String resultStr = null;
        try {
//			InputStream is = new FileInputStream(file);
//			String fileName = file.getName();
//			Long fileSize = file.length();
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getInputStream().available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(file.getContentType());
//			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            //上传文件
//			PutObjectResult putResult = ossClient.putObject(bucketName, bucketName + fileName, is, metadata);
            //System.out.println();
            System.out.println(file.getOriginalFilename());
            String s = bucketName+"/"+ RandomStringUtils.randomNumeric(6)+file.getOriginalFilename();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,s, file.getInputStream(), metadata);
            PutObjectResult putResult = ossClient.putObject(putObjectRequest);
            //十年
            resultStr = ossClient.generatePresignedUrl(bucketName, s, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10)).toString();
            //System.out.println(resultStr.trim());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传阿里云OSS服务器异常." + e.getMessage()+ e);
        }
        return resultStr;
    }
    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     *  最大20m
     *  超过20m请用 upload Exception:imgsize
     * @return
     * @throws Exception
     */
    public String img(MultipartFile img) throws Exception {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        if(img.getSize()>(20*1024*1024)){
            throw new Exception("img size>"+20*1024*1024);
        }
        try {
            String path= UUID.randomUUID().toString().replaceAll("-","");
            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(img.getOriginalFilename());
            ossClient.putObject(bucketName,buff.toString(), img.getInputStream());
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 365);
            //该地址 有效时间 365天
            //Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 );
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName,buff.toString(), HttpMethod.GET);
            String style = "image/resize,m_fixed,w_100,h_100";
            req.setExpiration(cal.getTime());
            req.setProcess(style);
            //url = ossClient.generatePresignedUrl(bucketName,str + "/"+path+"/"+key, cal.getTime()).toString();
            url=ossClient.generatePresignedUrl(req).toString();
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
    /**
     * 同步提交
     * @param input
     * @param key
     * @return
     */
    public String upload(InputStream input, String key) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        try {
            String path= UUID.randomUUID().toString().replaceAll("-","");
            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(key);
            ossClient.putObject(bucketName, buff.toString(), input);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 365);
            //该地址 有效时间 365天
            //Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 );
            url = ossClient.generatePresignedUrl(bucketName,buff.toString(), cal.getTime()).toString();
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
        }
        return url;
    }

    public String upload(byte[] input, String key) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        try {
            String path= UUID.randomUUID().toString().replaceAll("-","");

            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(key);
            ossClient.putObject(bucketName, buff.toString(),new ByteArrayInputStream(input));
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 365);
            //该地址 有效时间 365天
            url = ossClient.generatePresignedUrl(bucketName,buff.toString(), cal.getTime())
                    .toString();
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
        }
        return url;
    }


    /**
     * 同步提交
     * @return
     */
    public String uploadimg(MultipartFile img) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(img.getSize());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(img.getOriginalFilename()));
            String path= UUID.randomUUID().toString().replaceAll("-","");

            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(img.getOriginalFilename());
            ossClient.putObject(bucketName,buff.toString(), img.getInputStream(), metadata);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 365);
            url = ossClient.generatePresignedUrl(bucketName, buff.toString(), cal.getTime())
                    .toString();
        } catch (OSSException | ClientException | IOException e) {
            e.printStackTrace();
        }
        return url;
    }
    /**
     * 同步提交
     * @return
     */
    public String uploadimgBy1Day(MultipartFile img) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(img.getSize());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(img.getOriginalFilename()));
            String path= UUID.randomUUID().toString().replaceAll("-","");

            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(img.getOriginalFilename());
            ossClient.putObject(bucketName,buff.toString(), img.getInputStream(), metadata);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 1);
            url = ossClient.generatePresignedUrl(bucketName, buff.toString(), cal.getTime())
                    .toString();
        } catch (OSSException | ClientException | IOException e) {
            e.printStackTrace();
        }
        return url;
    }
    /**
     * 同步提交
     * @param input
     * @param key
     * @return
     */
    public String uploadimg(InputStream input, String key) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentEncoding("utf-8");
        metadata.setContentType(getContentType(key));
        String path= UUID.randomUUID().toString().replaceAll("-","");

        StringBuffer buff=new StringBuffer();
        buff.append(str);
        buff.append( "/");
        buff.append(path);
        buff.append("/");
        buff.append(key);
        ossClient.putObject(bucketName,buff.toString(), input, metadata);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 365);
        url = ossClient.generatePresignedUrl(bucketName, buff.toString(), cal.getTime()).toString();
        return url;
    }

    public String upload(MultipartFile img) {
        String str = ParseDate.newdate().split(" ")[0];
        String url = "";
        try {

            String path= UUID.randomUUID().toString().replaceAll("-","");
            StringBuffer buff=new StringBuffer();
            buff.append(str);
            buff.append( "/");
            buff.append(path);
            buff.append("/");
            buff.append(img.getOriginalFilename());

            ossClient.putObject(bucketName, buff.toString(), img.getInputStream());
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 365);
            url = ossClient.generatePresignedUrl(bucketName,buff.toString(), cal.getTime())
                    .toString();
        } catch (OSSException | ClientException | IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    public boolean delfile(String url) {
        try {
            String red = url.split("\\?")[0];
            int let = red.indexOf("/", red.indexOf("/", red.indexOf("/") + 1) + 1) + 1;
            String str = red.substring(let);
            ossClient.deleteObject(bucketName, str);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        // 默认返回类型
        return "image/jpeg";
    }

}
